/**
 * Created by zhanglihe on 15/11/3.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog',
    'datepicker'
], function( $, common, ready, template, Model, dialog, datepicker ) {
    var other_file = 0;
    var index = function() {
        this.init();
    };

    index.prototype = {
        init: function() {
            var _this = this;

            //地区
            $.ajax({
                url: _global.url.api + 'regions',
                type: 'get',
                async: false,
                data: {depth: 2},
                success: function(res) {
                    if(res.code == 0) {
                        _this.set('region', res.data);
                    }
                }
            });

            this.fetch();
        },
        fetch: function() {
            var that = this;
            var id = getUrlPath(3);
            this.model = new Model({
                url: _global.url.api + 'apply/' + id,
                data: {},
                render: function() {
                    $('#main-view').html(template('edit-tpl', {region: that.region, site: this.data}));
                    that.event();
                }
            });
            this.model.fetch();
        },
        set: function($k, $v) {
            this[$k] = $v;
        },
        event: function() {
            var _this = this;

            //地区联动
            $('.province').on('change', function() {
                $('select[name="city"]').html('');
                var id = $(this).val();
                var city = _this.region[id].child;
                for(var n in city) {
                    $('select[name="city"]').append('<option value="'+city[n].id+'">'+city[n].name+'</option>')
                }
            });
            if(_this.model.data.province > 0) {
                var city = _this.region[_this.model.data.province].child;
                for(var n in city) {
                    var selected = '';
                    if(_this.model.data.city == city[n].id) {
                        selected = 'selected';
                    }
                    $('select[name="city"]').append('<option value="'+city[n].id+'" '+selected+'>'+city[n].name+'</option>');
                }
            }

            $('input,select,textarea').on('change', function(e) {
                _this.change(e);
            });

            //测试号，显示登录帐号区域
            $('input[name="is_test"]').on('click', function() {
                var input_value=$(this).val();
                if (input_value==1){
                    document.getElementById("login_area").style.display='block';
                }else{
                    document.getElementById("login_area").style.display='none';
                }
            });

            //保存事件
            $('#btn-save').on('click', function(e) {
                e.preventDefault();
                if (_this.model.data.cate_id == undefined || _this.model.data.cate_id == []) {
                    alert('请选择分类');
                    return false;
                }
                _this.model.data.other_file = other_file;
                _this.model.valid_config = {
                    'name': 'required'
                };
                if($('[name="password"]').val()!=undefined){
                    _this.model.data.password = $('[name="password"]').val();
                }
                _this.model.data.is_oversea = $('input[name="is_oversea"]').is(':checked') ? 1 : 0;
                _this.model.data.contact = $('[name="contact"]').val();
                _this.model.data.address = $('[name="address"]').val();
                _this.model.data.tel = $('[name="tel"]').val();
                _this.model.data.mobile = $('[name="mobile"]').val();
                
                if(_this.model.put()) {
                    //_this.fetch();
                }
            });

            //选择分类
            $('#btn-cate').on('click', function(e) {
                e.preventDefault();
                //一级分类
                _this.cate_form = $(template('cate-tpl', {}));
                //分类
                $.ajax({
                    url: _global.url.api + 'categorys',
                    type: 'get',
                    async: false,
                    data: {depth: 1},
                    success: function(res) {
                        if(res.code == 0) {
                            $.each(res.data, function(n,v) {
                                _this.cate_form.find('[name="cate"]').append('<option value="'+ v.id +'">'+ v.name +'</option>');
                            });
                        }
                    }
                });

                //显示二级分类，并联动
                //bind change event
                _this.cate_form.find('[name="cate"]').on('change', function() {
                    _this.cate_form.find('[name="child-cate"]').html('');
                    var id = typeof $(this).val() == 'object' ? $(this).val()[0] : $(this).val();
                    $.ajax({
                        url: _global.url.api + 'categorys',
                        type: 'get',
                        async: false,
                        data: {depth: 1,pid:id},
                        success: function(res) {
                            if(res.code == 0) {
                                $.each(res.data, function(n,v) {
                                    _this.cate_form.find('[name="child-cate"]').append('<option value="'+ v.id +'">'+ v.name +'</option>');
                                });
                            }
                        }
                    });

                });
                //显示弹框
                _this.dialog = dialog({
                    content: _this.cate_form,
                    width: 400,
                    ok: function() {
                        isAdd = false;
                        $.each(_this.cate_form.find('select[name="child-cate"]')[0].selectedOptions, function(n,option) {
                            console.log('_this.model.data.cate_id',typeof(_this.model.data.cate_id));
                            if(typeof(_this.model.data.cate_id)=='string'){
                                _this.model.data.cate_id = JSON.parse(_this.model.data.cate_id);
                            }
                            $.each(_this.model.data.cate_id,function(n,v){
                                if(v==option.value){
                                    alert('该分类已添加');
                                    isAdd = true;
                                    return false;
                                }
                            });
                            if(isAdd){
                                return false;
                            }
                            var el_cate = $('<span class="label label-info mr10" id="'+option.value+'">'+option.text+
                            ' <a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                            $('#cate-name').append(el_cate);
                            _this.change_cate(option.value, 'add');
                        });
                        _this.cate_form.remove();

                    },cancel: function() {}
                }).show(e.target);
            });

            //分类删除
            $('#cate-name').find('a').on('click', function(e) {
                e.preventDefault();
                $(this).parent().remove();
                _this.change_cate($(this).parent().attr('id'), 'del');
            });

            $('body').on('click', '#btn-upload', function(e) {
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function() {
                        var affix = $("#upload-frame")[0].contentWindow.affix.get();
                        _this.affixPreview(affix);
                    }, cancel: function() {}
                });
                _this.upload_dialog.show();
            });
        },
        change: function(e) {
            this.model.data[$(e.target).attr('name')] = $(e.target).val();
        },
        affixPreview: function(affix) {
            console.log('this.data',affix);
            if(typeof affix.id !== 'undefined') {
                other_file = affix.id;
                $('#img-view').html(template('affix-tpl', affix));
            }
        },
        /**
         * 更改cate_id
         *
         * @param id
         * @param method (add: 增加, del: 移除)
         */
        change_cate: function(id, method) {
            var _this = this;
            //初始化cate_id
            if(typeof _this.model.data.cate_id == 'undefined') {
                _this.model.data.cate_id = [];
                $.each(_this.model.data.category_relation, function() {
                    _this.model.data.cate_id.push(this.cate_id);
                });
            }
            if(method == 'add') {
                _this.model.data.cate_id.push(id);
            } else {
                _this.model.data.cate_id.remove(id);
            }
        }
    };

    new index();

});